/**
 * 
 */
package org.dbwebx.gwt.mvp.presenter;

import java.util.List;

import org.dbwebx.domain.SourceNode;
import org.dbwebx.gwt.mvp.event.EventConstant;
import org.dbwebx.gwt.mvp.view.ITreeManageView;
import org.dbwebx.service.dao.SourceNodeServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.widgets.tree.TreeNode;

/**
 * @author Izzet_Mustafayev
 * 
 */
public class TreeManagePresenter extends BasePresenter<ITreeManageView> {

	private SourceNodeServiceAsync sourceNodeService;

	/**
	 * @param sourceNodeService
	 *            the sourceNodeService to set
	 */
	public void setSourceNodeService(
			final SourceNodeServiceAsync sourceNodeService) {
		changeServiceEntryPoint(sourceNodeService);
		this.sourceNodeService = sourceNodeService;
	}

	public void onStart() {
		view.setRootNode("Source Nodes");
		sourceNodeService.list(new AsyncCallback<List<SourceNode>>() {

			public void onSuccess(final List<SourceNode> sourceNodes) {
				fillTree(sourceNodes);
			}

			public void onFailure(Throwable caught) {
				GWT.log("Error occured on retrieveing source node list.",
						caught);
				view.addItem(new TreeNode("There are no source nodes."));
			}
		});

		eventBus.dispatch(EventConstant.ADD_TREE_PANEL, view);
	}

	/**
	 * Creates tree from given {@link SourceNode}s.
	 * 
	 * @param sourceNodes
	 *            the {@link SourceNode} list
	 */
	private void fillTree(final List<SourceNode> sourceNodes) {
		if (!sourceNodes.isEmpty()) {
			for (SourceNode sourceNode : sourceNodes) {
				TreeNode item = new TreeNode(sourceNode.getName());
				item.setTooltip(sourceNode.getName());
				if (null != sourceNode.getParent()) {
					item.setText(item.getText() + " has parent");
				}
				view.getNode(0).appendChild(item);
			}
		}
	}
}
